package org.smart4j.aopdemo.custom;


import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.List;

/**
 * 代理链式反应类
 */
public class ProxyChain {

    //所以需要运行的代理列表
    private List<Proxy> proxyList;

    //运行Proxy列表指针或者索引
    private int currentProxyIndex = 0;

    //原类，对象，方法及方法参数
    private Class<?> targetClass;

    private Object targetObject;

    private Method targetMethod;

    private Object[] methodParams;

    //代理方法
    private MethodProxy methodProxy;

    //代理方法执行结果
    private Object methodResult;

    public ProxyChain(List<Proxy> proxyList, Class<?> targetClass, Object targetObject, Method targetMethod, Object[] methodParams, MethodProxy methodProxy) {
        this.proxyList = proxyList;
        this.targetClass = targetClass;
        this.targetObject = targetObject;
        this.targetMethod = targetMethod;
        this.methodParams = methodParams;
        this.methodProxy = methodProxy;
    }

    public Class<?> getTargetClass() {
        return targetClass;
    }

    public Object getTargetObject() {
        return targetObject;
    }

    public Method getTargetMethod() {
        return targetMethod;
    }

    public Object[] getMethodParams() {
        return methodParams;
    }

    public MethodProxy getMethodProxy() {
        return methodProxy;
    }

    public Object getMethodResult() {
        return methodResult;
    }

    public void doProxyChain() throws Throwable {
        //如果代理链里有未完成的代理，执行代理
        if(currentProxyIndex<proxyList.size()){
            //执行下一个代理
            proxyList.get(currentProxyIndex++).doProxy(this);
        }else{
            //代理执行完成，返回实现的方法执行结果
            try {
                methodResult = methodProxy.invokeSuper(targetObject, methodParams);
            } catch (Throwable throwable) {
                 throw throwable;
            }
        }
    }

}
